package xyz.zcxsythenew.msec

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import androidx.navigation.fragment.findNavController
import com.google.android.material.snackbar.Snackbar
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder

/**
 * A simple [Fragment] subclass as the default destination in the navigation.
 */
class FirstFragment : Fragment() {

    private fun getIdFromJson(json: String) : String {
        val startIndex = json.indexOf(':') + 1
        val endIndex = json.indexOf(',')
        return json.substring(startIndex, endIndex)
    }

    override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        view.findViewById<Button>(R.id.button_first).setOnClickListener {
            val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
            imm?.hideSoftInputFromWindow(view.windowToken, 0)
            Thread(Runnable {
                val name = view.findViewById<EditText>(R.id.edittext_name).text.toString()
                val password = view.findViewById<EditText>(R.id.edittext_password).text.toString()
                val queryName = URLEncoder.encode(name, "UTF-8")
                val queryPassword = URLEncoder.encode(password, "UTF-8")
                val url = URL("http://192.168.1.10:7001/signup?name=$queryName&password=$queryPassword")
                val connection = url.openConnection() as HttpURLConnection
                connection.run {
                    requestMethod = "GET"
                    connect()
                    if (responseCode == HttpURLConnection.HTTP_CREATED) {
                        val json = StreamToString.readStream(inputStream)
                        activity?.runOnUiThread {
                            Snackbar.make(it, "Your id is: " + getIdFromJson(json), Snackbar.LENGTH_LONG).show()
                        }
                    }
                    disconnect()
                }
            }).start()
        }
    }
}